﻿#include"XQFileTableWidget.h"
#include"XQAlgorithm.h"
#include"MyTableSizeItem.h"
#include"XMD5.h"
#include<QTableWidget>
#include<QFileIconProvider>
#include<QDesktopServices>
#include<QMessageBox>
#include<QDir>
#include<QUrl>
#include<QMessageBox>
#include<QDebug>

//插入本地文件到表格
void XQFileTableWidget::insertLocalFileToTable(const fileInfo& info)
{
    //表格列数
    size_t  column= columnCount();
    // 获取表格的行数
    size_t row = this->rowCount();
    if(column>0)
    {
        // 在最后一行插入一行
        this->insertRow(row);
        //设置单元格图标
        auto ico = new QTableWidgetItem();
        QFileIconProvider provider;
        QIcon icon = provider.icon(QFileInfo(info.file_path));
        //当前是图片的话
        if (QStringList(IMAGENAMEFILTERS).indexOf("*." + QFileInfo(info.file_path).suffix()) != -1)
        {
            icon = QIcon(QFileInfo(info.file_path).filePath());
        }
        ico->setIcon(icon);
        ico->setFlags(Qt::NoItemFlags);
        ico->setData(Qt::UserRole, icon);
        //ico->setForeground(Qt::black); // 设置前景色为黑色
       // ico->setBackground(Qt::white); // 设置背景色为白色
        this->setItem(row, Type::icon, ico);
    }
    if (column > 1)
    {
        // 设置单元格名字
        auto name = new QTableWidgetItem(info.name);
        name->setData(Qt::UserRole, info.file_path);
        name->setData(FILEMD5, info.md5);
        name->setTextAlignment(Qt::AlignCenter);
        this->setItem(row, Type::name, name);
        if(!m_changeNameFlag)
            name->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
    }
    if (column > 2)
    {
        //设置文件大小
        auto size = new MyTableSizeItem(readableFileSize(info.fileSize));
        size->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
        size->setData(Qt::UserRole, info.fileSize);
        size->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
        //size->setFlags(size->flags()| Qt::ItemIsSelectable);
        this->setItem(row, Type::size, size);
    }
    if (column > 3)
    {
        //设置本地
        auto locality = new QTableWidgetItem("本地");
        locality->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); 
        locality->setTextAlignment(Qt::AlignCenter);
        locality->setData(FILEEXIST, true);
        this->setItem(row, Type::locality, locality);
    }
    if (column >4)
    {
        //设置云端
        auto cloud = new QTableWidgetItem("无");
       /* QString name= info.fileName();*/
        cloud->setData(FILEEXIST, false);
        if (m_cloudFile.find(info.md5) != m_cloudFile.end())
        {
            cloud->setText("云端");
            cloud->setData(FILEEXIST, true);
        }
        cloud->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
        cloud->setTextAlignment(Qt::AlignCenter);
        this->setItem(row, Type::cloud, cloud);
    }
}
void XQFileTableWidget::insertCloudFileToTable(const fileInfo& info)
{
    //表格列数
    size_t  column = columnCount();
    // 获取表格的行数
    size_t row = this->rowCount();
    if (column > 0)
    {
        // 在最后一行插入一行
        this->insertRow(row);
        //设置单元格图标
        auto ico = new QTableWidgetItem();
        QFileIconProvider provider;
        QIcon icon ;
        //当前是图片的话
        if (QStringList(IMAGENAMEFILTERS).indexOf("*." + QFileInfo(info.name).suffix()) != -1)
        {
            /*icon = QIcon(info.filePath());*/
        }
        ico->setIcon(icon);
        ico->setFlags(Qt::NoItemFlags);
        ico->setData(Qt::UserRole, icon);
        //ico->setForeground(Qt::black); // 设置前景色为黑色
       // ico->setBackground(Qt::white); // 设置背景色为白色
        this->setItem(row, Type::icon, ico);
    }
    if (column > 1)
    {
        // 设置单元格名字
        auto nameItem = new QTableWidgetItem(info.name);
        nameItem->setData(Qt::UserRole, info.file_path);//服务器位置地址好了
        nameItem->setData(FILEMD5, info.md5);
        nameItem->setTextAlignment(Qt::AlignCenter);
        this->setItem(row, Type::name, nameItem);
        if (!m_changeNameFlag)
            nameItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
    }
    if (column > 2)
    {
        //设置文件大小
        auto size = new MyTableSizeItem(readableFileSize(info.fileSize));
        size->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
        size->setData(Qt::UserRole, info.fileSize);
        size->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
        //size->setFlags(size->flags()| Qt::ItemIsSelectable);
        this->setItem(row, Type::size, size);
    }
    if (column > 3)
    {
        //设置本地
        auto locality = new QTableWidgetItem("无");
        locality->setData(FILEEXIST, false);
        locality->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
        locality->setTextAlignment(Qt::AlignCenter);
        this->setItem(row, Type::locality, locality);
    }
    if (column > 4)
    {
        //设置云端
        auto cloud = new QTableWidgetItem("云端");
        cloud->setData(FILEEXIST, true);
        cloud->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
        cloud->setTextAlignment(Qt::AlignCenter);
        this->setItem(row, Type::cloud, cloud);
    }
}
//从表格中删除已经删除的文件项
static void removeFileRow(QTableWidget* Table, const QStringList& tableList)
{
    for (auto& name : tableList)
    {
        // 遍历行
        for (int row = 0; row < Table->rowCount(); row++) {
            // 获取单元格指针
            QTableWidgetItem* item = Table->item(row, XQFileTableWidget::Type::name);
            if (item) {
                // 获取单元格数据
                if (name == item->text())//找到了
                {
                    Table->removeRow(row);
                    //qInfo() << "删除:"<< item->text();
                    break;
                }
            }
        }
    }
}
//从表格中获取文件的名字输出成列表
QStringList XQFileTableWidget::tableFileName()
{
    QStringList list;
    // 遍历行
    for (int row = 0; row < rowCount(); row++) {
        // 获取单元格指针
        QTableWidgetItem* item = this->item(row, Type::name);
        if (item) {
            // 获取单元格数据
            list << item->text();
        }
    }
    //list.sort();
    return std::move(list);
}
size_t XQFileTableWidget::addFile(const QStringList& fileList)
{
    //开始拷贝文件
    size_t count = 0;
    for (auto &filePath:fileList)
    {
        auto fileInfo = QFileInfo(filePath);
        //判断文件类型是不是对的
        if(!m_nameFilters.isEmpty())//文件过滤
        {
            if(m_nameFilters[0] != "*")
            {
                if (m_nameFilters.indexOf("*." + fileInfo.suffix()) == -1)//文件类型不对
                {
                    QString Text = QString("%1 大小:%2 文件类型错误\n支持的文件类型:%3\n请重新选择文件").arg(fileInfo.filePath()).arg(readableFileSize(fileInfo.size())).arg(m_nameFilters.join(","));
                    QMessageBox::information(nullptr, "提示", Text);
                    continue;
                }
            }
        }
        //判断单文件是否超了
        if (fileInfo.size() > m_fileMaxSize)//文件大小超过限制了
        {
            QString Text = QString("%1 大小:%2\n单文件最大:%3\n请压缩后或重新选择其他文件后重试").arg(fileInfo.filePath()).arg(readableFileSize(fileInfo.size())).arg(readableFileSize(fileMaxSize()));
            QMessageBox::information(nullptr,"提示", Text);
            continue;
        }
        //判断全部文件是否超了
        size_t fileSizes = tableFileSizeSum();//总大小
        if (fileInfo.size()+ fileSizes > m_fileSumMaxSize)//总文件大小超过限制了
        {
            QString Text = QString("%1 大小:%2\n已有文件%3 总文件最大:%4\n请压缩后或删除一些文件后重试").arg(fileInfo.filePath()).arg(readableFileSize(fileInfo.size())).arg(readableFileSize(fileSizes)).arg(readableFileSize(fileSumMaxSize()));
            QMessageBox::information(nullptr, "提示", Text);
            continue;
        }
        //以线程方式复制文件
        copyFileThreadInit(filePath, m_DirPath + "/" + fileInfo.fileName());
        ++count;
       /* if (QFile::copy(filePath, m_DirPath + "/" + fileInfo.fileName()))
            ++count;*/
    }
    return count;
}
size_t XQFileTableWidget::removeFile(const QStringList& fileList)
{
    size_t count = 0;
    for (auto& filePath : fileList)
    {
        if(QFile::remove(filePath))
        {
            ++count;

        }
    }
    return count;
}

void XQFileTableWidget::removeFile(int row)
{
    QString md5 = rowToMd5(row);
    QString filePath=item(row, Type::name)->data(Qt::UserRole).toString();
    QFile::remove(filePath);
    m_localFile.remove(md5);
    fileChange();
}

void XQFileTableWidget::removeAllRow()
{
    // 遍历行
    int count = rowCount();
    for (int row = 0; row < count; row++) {
        removeRow(0);
    }
}
void XQFileTableWidget::addCloudFile(const QString& name, const QString& md5, size_t size)
{
    fileInfo info;
    info.name = name;
    info.md5 = md5;
    info.fileSize = size;
    m_cloudFile[md5] = info;
}
void XQFileTableWidget::removeCloudFile(const QString& md5)
{
    m_cloudFile.remove(md5);
}
fileInfo& XQFileTableWidget::cloudFile(const QString& md5)
{
    return m_cloudFile[md5];
}
void XQFileTableWidget::clearCloudFile()
{
    m_cloudFile.clear();
}
void XQFileTableWidget::openFile()
{
    QString filePath=item(currentRow(), Type::name)->data(Qt::UserRole).toString();
    QFileInfo file(filePath);//打开文件
    //qInfo() << file.filePath();
    		// 打开文件
    QDesktopServices::openUrl(QUrl::fromLocalFile(file.filePath()));
}

void XQFileTableWidget::fileChange()
{
    //本地有文件变化
    QDir dir(m_DirPath);
    auto listInfo = dir.entryInfoList(m_nameFilters, QDir::Files, QDir::Name);
    /*auto tableList = tableFileName();*/
    //m_localFile.clear();
    removeAllRow();
    for (auto& info : listInfo)
    {
        auto fileName = info.fileName();
        QString md5 = XMD5::file(info.filePath().toLocal8Bit().toStdString()).c_str();
        if(m_localFile.find(md5)==m_localFile.end()|| m_localFile[md5].name== fileName)
        {
            m_localFile[md5] = fileInfo{ fileName,info.filePath(),md5,(size_t)info.size() };
            insertLocalFileToTable(m_localFile[md5]);
        }
        else if(m_localFile[md5].name != fileName)
        {
            QMessageBox::information(this, "添加文件", "添加的文件<"+ fileName+">与已有文件<"+m_localFile[md5].name+">内容一致,添加失败");
            QFile(info.filePath()).remove();
        }
      
        //// 查找字符串 
        //int index = tableList.indexOf(info.fileName());
        //if (index == -1)//这是新增加的文件
        //{
        //    insertLocalFileToTable(m_localFile[fileName]);
        //}
        //else//已经有了
        //{
        //    tableList.remove(index);
        //}
       
    }
    //if (!tableList.isEmpty())//这几个都是被删除的文件
    //{
       //removeFileRow(this, tableList);
    //}



    //准备插入云端的文件
    auto clouds=m_cloudFile.keys();
    for (auto& md5:clouds)
    {
        if (m_localFile.find(md5) == m_localFile.end())//这是新增加的文件
        {
            insertCloudFileToTable(m_cloudFile[md5]);
        }
    }

    //SetColumnWidth(1);//设置文件名列宽
    SetColumnWidth(Type::size);//设置文件大小列宽
    // 刷新表格
    viewport()->update();
    emit tableFileChange();
}
